import type { App } from "vue";
import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
  RouteRecordRaw,
} from "vue-router";
import { useAdminStoreWithOut } from "../store/modules/admin";
import { umsAdmin } from "../request/http";

const adminStore = useAdminStoreWithOut();
// let a: number;
// let b: number | string;

// a = b;
// b = a; // 协变

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../pages/login/index.vue"),
  },
  // {
  //   path: "/homepage",
  //   name: "homepage",
  //   component: () => import("../pages/homepage/index.vue"),
  // },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 前置导航守卫
router.beforeEach(async (to, from, next) => {
  // token && menu.length === 0
  const token = localStorage.getItem("token");
  // console.log(adminStore.menus.length);
  if (token && adminStore.menus.length === 0) {
    // 发送请求获取当前登录用户信息
    const adminData = await umsAdmin.getAdminInfo();
    if (adminData.code === 200) {
      adminStore.updateMenus(adminData.data.menus);
      // 生成动态路由规则
      const newMenus = adminStore.genNewMenus;
      for (let key in newMenus) {
        let menuObj: RouteRecordRaw = {
          path: "/" + newMenus[key].name,
          name: newMenus[key].name,
          component: () => import("../pages/homepage/index.vue"),
          children: [],
        };
        newMenus[key].children.forEach((submenu) => {
          menuObj.children?.push({
            path: submenu.name,
            name: submenu.name,
            component: () =>
              import(
                `../pages/${newMenus[key].name}/${submenu.name}/index.vue`
              ),
          });
        });

        // console.log(menuObj);
        // 添加到路由里面
        router.addRoute(menuObj);
      }

      // 添加首页路由
      router.addRoute({
        path: "/",
        name: "home",
        redirect: "/index",
        component: () => import("../pages/homepage/index.vue"),
        children: [
          {
            path: "index",
            name: "index",
            component: () => import("../pages/index/index.vue"),
          },
        ],
      });

      return next(to);
    } else {
      // 删掉token，重定向login
      localStorage.clear();
      return next("/login");
    }
  } else if (token && to.path === "/login") {
    return next(from);
  } else if (!token && to.path !== "/login") {
    return next("/login");
  } else {
    return next();
  }
});

export function initRouter(app: App<Element>) {
  app.use(router);
}

// export default router;
